<template>
  <BasicForm @register="registerForm" >
    <template #spec="{ model, field }">
      <a-row :gutter="8">
        <a-col :sm="24" :md="24" :lg="24" :xl="24" class="goods-spec-type">
          <a-radio-group v-model:value="model[field]">
            <a-radio :value="true">多规格</a-radio>
            <a-radio :value="false">统一规格</a-radio>
          </a-radio-group>
        </a-col>
        <a-col :sm="24" :md="24" :lg="24" :xl="24">
          <MyCardGroup v-model:value="state.specList" width="96%" v-if="model[field] === true" style="margin-top: 10px;"
            :minCardNumber="0" addCardButtonName="添加规格" :isInitOne="false" 
            :defaultData="specCardDefaultData" :beforeAdd="handleBeforeAddSpec"
            delete-title="删除此规格将丢失本次编辑内容, 是否删除?" :before-delete="handleBeforeDeleteSpec"
            @remove="handleRemoveCardGroup">
            <template v-slot="{ data }">
              <SelectSpec :spec="data" :is-update="state.isUpdate" :sku-list="state.skuList"  @change="handleSelectSpec"/>
            </template>
          </MyCardGroup>
        </a-col>
      </a-row>
    </template>

    <template #skuList="{ model, field }">
      <SkuStock :selectSpecList="state.specList" v-model:value="state.skuList" :isUpdate="state.isUpdate"/>
    </template>
  </BasicForm>
</template>
<script lang="ts" setup>
import {reactive, ref, unref, useAttrs, watch} from 'vue';
import {BasicForm, useForm} from '/@/components/Form/index';
import {formSchema} from './goods.data';
import SelectSpec from './SelectSpec.vue';
import SkuStock from './SkuStock.vue';
import {useMessage} from '/@/hooks/web/useMessage';
import {list as listGoodsCategory} from "../goodsCategory/category.api";
import MyCardGroup from '/@/components/Form/src/my/components/MyCardGroup.vue';
import {toCompSelectSpecList} from './assembly';
import {isArray} from 'lodash';
import {GoodsProps, GoodsState} from './type';

const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);

const attrs = useAttrs()
const state = reactive<GoodsState>({
  skuList: [],
  specList: [],
  isUpdate: false,
  detailContent: ''
})

const specCardDefaultData = ref({
  specId: '',
  values: [],
  name: ''
})

const props = defineProps(GoodsProps)
const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate }] = useForm({
  labelCol: {
    md: { span: 6 },
    sm: { span: 6 },
  },
  wrapperCol: {
    md: { span: 22 },
    sm: { span: 22 },
  },
  labelWidth: 90,
  schemas: formSchema,
  showActionButtonGroup: false
});

watch(
  () => props.specList,
  async (data: any) => {
    await resetFields()
    toCompSelectSpecList(props.specList).forEach(e => handleSelectSpec(e))
    handleSelectSpec([])

    state.skuList = props.skuList || []

    state.isUpdate = props.isUpdate;
    console.log("use data: ", props);
    if (state.isUpdate) {
      setFieldsValue({ ...props })
    }
    
    const treeData = await listGoodsCategory({})
    updateSchema([
      { field: 'goodsCategoryId', componentProps: { treeData } }
    ])
  },
  { deep: true }
)

//提交事件
async function getData() {
  try {
    const values = await validate()
    const ret = {
      ...values, 
      specList: unref(state.specList).map(e => {
        // 拷贝数据
        const newObj = JSON.parse(JSON.stringify(e))
        return {...newObj}
      }), 
      skuList: unref(state.skuList).map(e => { 
        console.log('skuItem: ', e);
        
        delete e.tempId
        for (let key in e) {
          if (key.includes('sku_')) {
            delete e[key]
          }
        }
        return {
          ...e, 
          specData: JSON.parse(e.specData)
        }
      })
    };
    return ret
  } finally {
    
  }
}

const handleRemoveCardGroup = (value) => {
  console.log('handleRemoveCardGroup', value);
  state.specList = state.specList.filter(e => e.specId !== value.specId)
}

const handleSelectSpec = (value) => {
  if (isArray(value)) {
    return
  }
  // 这里去重
  const tempMap = new Map()
  state.specList.forEach(e => { tempMap.set(e.specId, e) })
  tempMap.set(value.specId, value)

  state.specList = Array.from(tempMap.values()).filter(e => e.specId !== '')
  console.log('handleSelectSpec', state.specList);
} 

const handleBeforeAddSpec = () => {
  if (!state.skuList ||state.skuList.length == 0) {
    return true
  }
  // console.log('state.skuList', state.skuList)
  
  // const stockList = state.skuList?.flatMap(e => e.stockList).map(e => e.stock)
  // let totalStock = stockList && stockList.length > 0 ? stockList.reduce((e1, e2) => e1 + e2) : 0
  // if (totalStock > 0) {
  //   createMessage.error('需要商品所有规格的库存都为0时，才能添加规格。如需添加，请先调整库存')
  //   return false
  // }
  return true
}

const handleBeforeDeleteSpec = (spec) => {
  console.log('deletedSpec', spec);
  if (!state.skuList ||state.skuList.length == 0) {
    return true
  }
  
  // console.log('state.skuList', state.skuList)
  // let totalStock = state.skuList?.filter(e => spec.values.filter(e1 => e.specData.includes(e1)))
  //                 .flatMap(e => e.stockList).map(e => e.stock).reduce((e1, e2) => e1 + e2)
  // if (totalStock > 0) {
  //   createMessage.error('需要商品所有规格的库存都为0时，才能删除规格。如需添加，请先调整库存')
  //   return false
  // }
  return true
}

defineExpose({
  getData
})
</script>

<style lang="less">
.goods-spec-type {
  // display: flex;
}

</style>

